<template>
  <div class="wrapper">
    <div
      v-if="waybillInfo.status >= 2 && waybillInfo.payment === '6'"
      style="position: absolute; left: 600px; top: 100px; z-index: 10"
    >
      <div v-if="!showPaymentBtn">
        收款：<el-button
          v-if="waybillInfo.pay_status === '0' && !paySuccess"
          id="openPayment"
          @click="openPayment"
          >出示收款码</el-button
        >
        <span v-else>{{ PAY_STATUS[waybillInfo.pay_status] }}</span>
      </div>

      <div v-else>
        <div style="text-align: center; margin-right: 0px">
          <span
            class="icon iconfont icon-weixin"
            style="color: #28c445; margin-right: 10px; font-size: 20px"
          ></span
          >微信支付
        </div>
        <el-image v-if="!paySuccess" :src="qrcodeUrl" fit="cover"></el-image>
        <el-result v-else icon="success" title="支付成功"> </el-result>
        <div style="margin-left: 125px">
          <el-button type="primary" @click="closeQrcode">关 闭</el-button>
        </div>
      </div>
    </div>
    <div class="step-sign" style="padding: 20px 20px">
      <el-form
        :model="ruleForm"
        :key="ruleForm.id"
        :rules="rules"
        ref="ruleForm"
        label-width="220px"
        class="demo-ruleForm inputForm"
        :disabled="disable"
      >
        <el-form-item label="" prop="sign_name">
          <el-radio-group size="medium" v-model="ruleForm.sign_type">
            <el-radio-button id="sign_cmd" label="0">签收</el-radio-button>
            <el-radio-button id="un_sign_cmd" label="1">拒收</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <template v-if="ruleForm.sign_type === '0'">
          <el-form-item label="签收人" prop="sign_name">
            <el-input id="sign_name" v-model="ruleForm.sign_name"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="id_card">
            <el-input id="id_card" v-model="ruleForm.id_card"></el-input>
          </el-form-item>
          <el-form-item label="签收方式" prop="confirm_type">
            <el-select
              id="confirm_type_down"
              v-model="ruleForm.confirm_type"
              filterable
              placeholder="请选择"
            >
              <el-option
                id="confirm_type"
                v-for="item in signData"
                :label="item.value"
                :value="item.key + ''"
                :key="item.key"
                >{{ item.value }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item label="签收时间" prop="sign_time">
            <el-date-picker
              id="sign_time"
              v-model="ruleForm.sign_time"
              value-format="timestamp"
              :default-value="Date.now()"
              :clearable="false"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="timeDisable"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="创建时间" prop="create_time">
            <el-date-picker
              v-model="ruleForm.create_time"
              clearable
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              :disabled="mode === 'edit' || mode === 'singleEdit'"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="客户回单上传" prop="images1" ref="imgRef1">
            <UploadFile
              id="upload_kh"
              :images.sync="ruleForm['images1']"
              :disabled="disable"
            ></UploadFile>
          </el-form-item>
          <el-form-item label="我司回单上传" prop="images0" ref="imgRef0">
            <UploadFile
              id="upload_ds"
              :images.sync="ruleForm['images0']"
              :disabled="disable"
            ></UploadFile>
          </el-form-item>
          <el-form-item label="温度报告上传" prop="images2">
            <UploadFile
              id="upload_wd"
              :images.sync="ruleForm['images2']"
              :disabled="disable"
            ></UploadFile>
          </el-form-item>
          <el-form-item label="其他单据上传" prop="images3">
            <UploadFile
              id="upload_qt"
              :images.sync="ruleForm['images3']"
              :disabled="disable"
            ></UploadFile>
          </el-form-item>
        </template>
        <template v-else>
          <el-form
            :model="ruleFormReject"
            :key="ruleFormReject.id"
            :rules="rulesReject"
            ref="ruleFormReject"
            label-width="220px"
            class="demo-ruleForm"
            :disabled="disable"
          >
            <el-form-item label="拒收人" prop="sign_name">
              <el-input
                id="reject_sign_name"
                v-model="ruleFormReject.sign_name"
              ></el-input>
            </el-form-item>
            <el-form-item label="拒收类型" prop="reject_type">
              <el-select
                id="reject_type_down"
                v-model="ruleFormReject.reject_type"
                filterable
                placeholder="请选择"
              >
                <template v-for="(val, index) in rejectData">
                  <el-option
                    id="reject_type"
                    v-if="val"
                    :label="val"
                    :value="index + ''"
                    :key="index + ''"
                    >{{ val }}</el-option
                  >
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="拒收原因" prop="reject_reason">
              <el-input
                id="reject_reason"
                v-model="ruleFormReject.reject_reason"
              ></el-input>
            </el-form-item>
            <el-form-item label="拒收时间" prop="sign_time">
              <el-date-picker
                id="reject_sign_time"
                v-model="ruleFormReject.sign_time"
                value-format="timestamp"
                :clearable="false"
                type="datetime"
                placeholder="选择日期时间"
                :disabled="timeDisable"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="附件" prop="images4">
              <UploadFile
                id="upload_fj"
                :images.sync="ruleFormReject['images4']"
                :disabled="disable"
              ></UploadFile>
            </el-form-item>
          </el-form>
        </template>
        <el-table
          :data="ruleForm['waybill_data']"
          style="width: 100%"
          border
          show-summary
          sum-text="汇总"
          class="safari_table"
        >
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column label="运单号">
            <template slot-scope="scope">
              {{ scope.row["waybill_no"] }}
            </template>
          </el-table-column>
          <el-table-column label="件数" prop="number">
            <template slot-scope="scope">
              <el-input v-model="scope.row['number']"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="重量（kg）" prop="newWeight">
            <template slot-scope="scope">
              <el-input v-model="scope.row['newWeight']"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="体积（m³）" prop="newVolume">
            <template slot-scope="scope">
              <el-input v-model="scope.row['newVolume']"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="包装数量" prop="package_quantity">
            <template slot-scope="scope">
              <el-input v-model="scope.row['package_quantity']"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <div
          style="margin-top: 20px; text-align: right; padding-bottom: 20px"
          v-if="!disable"
        >
          <el-button id="create_cancel" @click="$emit('close', false)"
            >取消</el-button
          >
          <el-button
            id="create_ok"
            type="primary"
            data-tracker="P4-4"
            @click="handleClickSubmit"
            v-preventReClick
            :loading="submitLoading"
            >保存</el-button
          >
        </div>
      </el-form>
    </div>
    <div>
      <notify
        v-if="notifyType"
        :noTifyData="noTifyData"
        :key="noTifyData.node_id"
      ></notify>
    </div>
  </div>
</template>

<script>
import {
  waybillRepo,
  getWaybillListFn,
  SignforAddFn,
  WaybillListForSign,
  SignforDetailFn,
  SignforEditFn,
  signforEditOne,
  SignTimeControl,
  WaybillWxPayQrcode,
  WaybillPaymentStatus,
} from "@/api/waybill";
import { uploading } from "@/page/material/common/common";
import { timestamp10 } from "@/utils/mUtils";
import UploadFile from "@/components/uploadFile/index.vue";
import { PAY_STATUS } from "@/utils/constants";
import notify from "@/components/notify/notify.vue"; // 时间转化
export default {
  name: "signfor",
  components: { UploadFile, notify },
  props: ["mode", "ids", "id", "type", "signType", "waybillInfo"],
  data() {
    return {
      submitLoading: false,
      showPaymentBtn: false,
      qrcodeUrl: "",
      ruleForm: {
        waybill_data: [],
        images: [],
        images1: [],
        images2: [],
        images3: [],
        images4: [], // 拒收附件
        images0: [],
        customer_images: [],
        sign_type: "0",
        sign_time: "",
        sign_name: "",
        confirm_type: "0", // 签收方式
        create_time: "", //创建时间
      },
      ruleFormReject: {
        images4: [], // 拒收附件
        sign_time: "",
        sign_name: "",
      },
      rules: {
        sign_name: [
          { required: true, message: "请填写签收人", trigger: "blur" },
        ],
        confirm_type: [
          { required: true, message: "请选择签收方式", trigger: "blur" },
        ],
        images0: [
          { required: true, message: "请上传我司回单", trigger: "blur" },
        ],
        images1: [
          { required: true, message: "请上传客户单据", trigger: "blur" },
        ],
      },
      rulesReject: {
        reject_reason: [
          { required: true, message: "请填写拒收原因", trigger: "blur" },
        ],
      },
      // paymentData: [],
      signData: [
        {
          key: "0",
          value: "签字",
        },
        {
          key: "1",
          value: "盖章",
        },

        {
          key: "2",
          value: "签字+盖章",
        },
      ],
      rejectData: ["", "客户原因", "我司原因"],
      fileList: [], //上传的文件
      dialogImageUrl: "",
      dialogVisible: false,
      timeDisable: false,
      timer: {},
      paySuccess: false,
      PAY_STATUS: PAY_STATUS,
      notifyType: false,
      noTifyData: {
        customer_id: "",
        product_type_id: "",
        node_id: "",
      },
    };
  },
  computed: {
    disable: function () {
      return this.mode === "detail" || this.mode === "singleDetail";
    },
  },
  watch: {
    id: {
      handler: function (val) {
        val && this.getDetail();
      },
      immediate: true,
    },
    mode: {
      handler: function () {
        this.handleChangeMode();
      },
      immediate: true,
    },
    "ruleForm.sign_type": function (val) {
      this.ruleFormReject.sign_type = val;
    },
    signType: {
      handler: function (val) {
        this.ruleForm.sign_type = val || "0";
      },
      immediate: true,
    },
    "ruleForm.images0": function (val) {
      this.$refs.imgRef0.clearValidate();
    },
    "ruleForm.images1": function (val) {
      this.$refs.imgRef1.clearValidate();
    },
  },
  mounted() {
    this.NotificationObj();
    // if (this.mode === "edit" || this.mode === "detail") {
    //   this.getDetail();
    // } else {
    //   this.initWaybillData();
    // }
  },
  destroyed() {
    clearTimeout(this.timer);
  },
  beforeMount() {
    this.handleChangeMode();
  },
  methods: {
    handleChangeMode() {
      if (this.mode === "edit" || this.mode === "detail") {
        this.getDetail();
      } else if (this.mode === "add") {
        this.initWaybillData();
        this.ruleForm.sign_name = this.waybillInfo.receiver_name;
        this.ruleFormReject.sign_name = this.waybillInfo.receiver_name;
        this.ruleForm.create_time = Date.now();
      }
      SignTimeControl({ waybill_id: this.waybillInfo.id }).then((res) => {
        const data = res.data || {};
        // 1是置灰   1是必填
        this.timeDisable = data.switch_status == "1" ? true : false;
        this.rules.images0[0].required = data.is_receipt_ds > 0 ? true : false;
        this.rules.images1[0].required =
          data.is_receipt_customer > 0 ? true : false;
        if (this.mode === "add") {
          const deaultSignTime = data.time * 1000 || Date.now();
          this.ruleForm.sign_time = deaultSignTime;
          this.ruleFormReject.sign_time = deaultSignTime;
        }
      });
    },
    getDetail() {
      SignforDetailFn({ id: this.id + "" }).then((res) => {
        const data = res.data;

        data.sign_time = data.sign_time * 1000;
        data.images = data.images || [];
        data.images0 =
          data.images
            .filter((item) => item.type === "10")
            .map((item) => item.url) || [];
        data.images1 =
          data.images
            .filter((item) => item.type === "11")
            .map((item) => item.url) || [];
        data.images2 =
          data.images
            .filter((item) => item.type === "12")
            .map((item) => item.url) || [];
        data.images3 =
          data.images
            .filter((item) => item.type === "13")
            .map((item) => item.url) || [];
        data.images4 =
          data.images
            .filter((item) => item.type === "14")
            .map((item) => item.url) || [];
        // this.fileList = data.images;
        // this.ruleForm.images = [...this.fileList];
        let ruleFormObj =
          data.sign_type === "0" ? this.ruleForm : this.ruleFormReject;
        data["waybill_data"].forEach((item) => {
          item.newWeight = item.weight + "";
          item.newVolume = item.volume + "";
        });
        data.create_time = data.create_time * 1000;

        this.ruleForm = data;

        this.ruleFormReject = this.ruleForm;
      });
    },
    initWaybillData() {
      let { ids = "[]" } = this.$route.query || {};
      ids = JSON.parse(ids);
      const _ids = this.ids || ids.map(Number);
      // getWaybillListFn({ ids: _ids, query_goods: "1" }).then((res) => {
      //   const list = [];
      //   res.data.data.forEach((item) => {
      //     const { sender_name, fromRegion_name, waybill_no, goods = [] } = item;
      //     let nums = 0,
      //       weight = 0,
      //       volume = 0;
      //     goods.forEach((g) => {
      //       nums += Number(g.number);
      //       weight += Number(g.weight);
      //       volume += Number(g.volume);
      //     });
      //     list.push({
      //       waybill_id: item.id,
      //       number: nums + "",
      //       money: 20 + "",
      //       weight: weight + "",
      //       volume: volume + "",
      //       waybill_no,
      //       sender_name,
      //       fromRegion_name,
      //     });
      //   });
      //   this.ruleForm["waybill_data"] = list;
      // });
      WaybillListForSign({ waybill_id_list: _ids }).then((res) => {
        if (res.data) {
          res.data.forEach((item) => {
            item.newWeight = item.weight + "";
            item.newVolume = item.volume + "";
          });
          this.ruleForm["waybill_data"] = res.data;
        }
      });
    },
    handleSelectionChange() {},
    formatImage(obj, images, type) {
      return obj[images].map((item) => {
        return { type, url: item };
      });
    },
    // 点击确定
    handleClickSubmit() {
      const formRefName =
        this.ruleForm.sign_type === "0" ? "ruleForm" : "ruleFormReject";
      this.$refs[formRefName].validate((valid) => {
        if (!valid) return;
        this.submitLoading = true;
        const images = [];
        let _ruleForm = {};
        // 签收
        if (this.ruleForm.sign_type === "0") {
          for (let i = 0; i < 4; i++) {
            images.push(
              ...this.formatImage(this.ruleForm, `images${i}`, String(10 + i))
            );
            _ruleForm = {
              ...this.ruleForm,
              images,
              sign_time: timestamp10(this.ruleForm.sign_time),
              create_time: timestamp10(this.ruleForm.create_time),
            };
          }
        } else if (this.ruleForm.sign_type === "1") {
          // 拒收
          images.push(
            ...this.formatImage(this.ruleFormReject, `images4`, "14")
          );
          _ruleForm = {
            ...this.ruleFormReject,
            waybill_data: this.ruleForm.waybill_data,
            images,
            create_time: timestamp10(this.ruleForm.create_time),
            sign_time: timestamp10(this.ruleFormReject.sign_time),
          };
        }
        _ruleForm.waybill_data &&
          _ruleForm.waybill_data.forEach((item) => {
            item.weight = item.newWeight + "";
            item.volume = item.newVolume + "";
          });
        if (this.mode === "add") {
          SignforAddFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              this.$message({
                message:
                  this.ruleForm.sign_type === "0" ? "签收成功" : "拒收成功",
                type: "success",
              });
              this.$emit("close");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        } else {
          const editFn =
            this.mode === "singleEdit" ? signforEditOne : SignforEditFn;
          editFn(_ruleForm).then((res) => {
            if (res && res.code === 10000) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$emit("close");
              this.submitLoading = false;
            } else {
              this.submitLoading = false;
              this.$message({
                message: res.message,
                type: "error",
              });
            }
          });
        }
      });
    },
    // 图片上传功能
    handleChange(file, fileList, type) {
      this.fileList = fileList;
      var filelist = file.raw; //文件
      var filename = file.raw.uid + file.raw.name; //通过 uid和name组成文件的名字
      uploading(filelist, filename, type).then((res) => {
        this.ruleForm.images.push({
          uid: file.uid,
          type: "0",
          url: res.res.requestUrls[0],
        });
      });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      const index = this.ruleForm.images.findIndex(
        (item) => item.uid === file.uid
      );
      index > -1 && this.ruleForm.images.splice(index, 1);
    },
    removeChange(file, fileList, type) {},
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async openPayment() {
      // console.log(this.waybillInfo, "================");
      let res = await WaybillWxPayQrcode({
        order_id: 0,
        waybill_id: this.waybillInfo.id * 1,
      });
      if (res.code !== 10000) {
        this.$message({
          message: res.message,
          type: "warning",
        });
      } else {
        this.qrcodeUrl = res.data.code_data;
        this.showPaymentBtn = true;
        let result;
        this.timer = setInterval(async () => {
          result = await WaybillPaymentStatus({
            waybill_id: this.waybillInfo.id * 1,
          });
          if (result.data.status === 1) {
            // this.$message({
            //   message: "支付成功",
            //   type: "success",
            // });
            clearTimeout(this.timer);
            this.paySuccess = true;
          }
        }, 2000);
      }
    },
    closeQrcode() {
      clearTimeout(this.timer);
      this.showPaymentBtn = false;
    },
    //Notification 通知事件
    NotificationObj() {
      // console.log("函数调用");
      // 数据改变
      (this.noTifyData = {
        customer_id: this.waybillInfo.customer_id + "",
        product_type_id: this.waybillInfo.waybill_product_type,
        node_id: "5",
      }),
        (this.notifyType = true);
    },
  },
};
</script>
<style lang="less" scoped>
//表格合计行置顶
/deep/ .el-table {
  display: flex;
  flex-direction: column;
}

/* order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方 */
/deep/ .el-table__body-wrapper {
  order: 1;
}
.wrapper {
  .step-sign .el-form-item {
    .el-input,
    .el-select {
      width: 200px;
    }
  }
}
</style>
